<?php
namespace app\controller\Admin;

use support\Request;
use support\Response;
use app\model\ProductCategory;

class ProductCategoryController
{
    /**
     * 获取分类列表
     * @param Request $request
     * @return Response
     */
    public function list(Request $request)
    {
        $query = ProductCategory::query();
        
        // 查询条件
        if ($name = $request->input('name')) {
            $query->where('name', 'like', "%{$name}%");
        }
        if ($status = $request->input('status')) {
            $query->where('status', $status);
        }
        if ($level = $request->input('level')) {
            $query->where('level', $level);
        }

        $data = $query->orderBy('sort', 'desc')
            ->orderBy('category_id', 'desc')
            ->paginate($request->input('limit', 15));

        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => $data
        ]);
    }

    /**
     * 添加分类
     * @param Request $request
     * @return Response
     */
    public function add(Request $request)
    {
        $data = $request->post();
        $category = new ProductCategory();
        $category->fill($data);
        
        if ($category->save()) {
            return json(['code' => 0, 'msg' => '添加成功']);
        }
        return json(['code' => 1, 'msg' => '添加失败']);
    }

    /**
     * 编辑分类
     * @param Request $request
     * @return Response
     */
    public function edit(Request $request)
    {
        $data = $request->post();
        $category = ProductCategory::find($data['category_id']);
        if (!$category) {
            return json(['code' => 1, 'msg' => '分类不存在']);
        }
        
        $category->fill($data);
        if ($category->save()) {
            return json(['code' => 0, 'msg' => '编辑成功']);
        }
        return json(['code' => 1, 'msg' => '编辑失败']);
    }

    /**
     * 删除分类
     * @param Request $request
     * @return Response
     */
    public function delete(Request $request)
    {
        $categoryId = $request->input('category_id');
        $category = ProductCategory::find($categoryId);
        if (!$category) {
            return json(['code' => 1, 'msg' => '分类不存在']);
        }

        // 检查是否有子分类
        $hasChildren = ProductCategory::where('parent_id', $categoryId)->exists();
        if ($hasChildren) {
            return json(['code' => 1, 'msg' => '请先删除子分类']);
        }

        if ($category->delete()) {
            return json(['code' => 0, 'msg' => '删除成功']);
        }
        return json(['code' => 1, 'msg' => '删除失败']);
    }
} 